//
//  MyCarInfoInputViewController.m
//  carcareIOS
//
//  Created by 王然 on 16/8/3.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "MyCarInfoInputViewController.h"
#import "BRCarInfoCitySeleCell.h"
#import "BRCarInfoCarBrandCell.h"
#import "BRCarInfoCarNumCell.h"
#import "BRCarStyleCell.h"

#import "BRSelectCityViewController.h"
#import "CarCityNamesView.h"
#import "ViolationCityMgr.h"


#import "MineCarsViewController.h"
#import "ChoiceCarInfoViewController.h"
#import "PersonInfoViewController.h"
#import "BingdingMyBoxCarViewController.h"
#import "NetCar.h"

#import "TipsInputView.h"
#import "PopExampleImageV.h"
#define SECTION_BIG_HEIGHT (14)
#define SECTION_TITLE_HEIGHT (27)
#define CELL_GRAY_HEIGHT (42)
#define CELL_BTN_HEIGHT (50)

@interface MyCarInfoInputViewController ()<BRSelectCityDelegate>

@property (nonatomic , strong) CarCityNamesView * carCityV;
//车牌号签名的城市背景黑色view
@property (nonatomic , strong) UIView * cityNamesBackV;
//车牌号签名的城市 而不是所查询的城市
@property (nonatomic , strong) UILabel * brandCityL;

@property (nonatomic , strong) UIImageView * brandRightImageV;

//车牌号
@property (nonatomic , strong) UITextField * brandNoTF;

//发动机号
@property (nonatomic , strong) UITextField * engineNOTF;

//车架号
@property (nonatomic , strong) UITextField * classNoTF;

@property (nonatomic , strong) CarModel * carModel;

@property (nonatomic , strong) CarModel * canChangeCarModel;//克隆出来了一个可以改变的carmodel 用于操作

@property (nonatomic , strong) ViolationCityMgr * cityMgr;

@property (nonatomic, copy) NSString * buttonTitle;
@property (nonatomic, copy) void (^ClickDone)();
@property (nonatomic, assign) BOOL isBinding;

@property (nonatomic , strong) PopExampleImageV * popExampleImageV;;//弹出样例图片

@property (nonatomic) BOOL willPushCarStyle;
@end

@implementation MyCarInfoInputViewController
- (instancetype)initWithInputType:(TYPE_INPUT)type carModel:(CarModel *)carModel
{
    self = [super initWithInputType:type];
    if (self) {
        self.willPushCarStyle = YES;
        self.buttonTitle = @"保存";
        self.carModel = carModel;
        self.canChangeCarModel = [[CarModel alloc] initWithDic:carModel.modelDic];
        self.canChangeCarModel.carinfoModel = [[CarInfoModel alloc] initWithDic:self.carModel.carinfoModel.modelDic];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"填写车辆信息";
    
    [self createTableView];
    
    __weak __typeof(self) wself = self;
    [self navSetupBackItemWithIdentification:BACK_ICON action:^{
        if(wself.willBackClick)wself.willBackClick(YES);
        [wself.navigationController popViewControllerAnimated:YES];
    }];
    
    self.cityMgr = VIOLATIONMGR;
    
    UIWindow * mainWindow = [UIApplication sharedApplication].delegate.window;
    
    [mainWindow addSubview:self.popExampleImageV];
    [self.popExampleImageV setHidden:YES];
    
    [mainWindow addSubview:self.cityNamesBackV];
    self.cityNamesBackV.userInteractionEnabled = YES;
    self.cityNamesBackV.hidden = YES;
    
    [self.cityNamesBackV addTapSingleAction:^(UITapGestureRecognizer *recognizer) {
        [wself clickOnBG];
    }];
    
    self.carCityV = [[CarCityNamesView alloc] initWithFrame:CGRectMake(0, __MAIN_HEIGHT, __MAIN_WIDTH, 346)];
    self.carCityV.Choice = ^(NSString *name){
        wself.canChangeCarModel.carinfoModel.carNoCityStr = name;
        if(wself.brandCityL)wself.brandCityL.text = name;
        if(wself.brandRightImageV)wself.brandRightImageV.transform = CGAffineTransformMakeRotation(0);
        [wself clickOnBG];
    };
    [self.cityNamesBackV addSubview:self.carCityV];
    self.carCityV.hidden = YES;
    
    if (self.isBinding) {
        
        self.willPushCarStyle = NO;
 
        [NetCar carListSuccess:^(NSArray<CarModel *> *cars) {
            if (cars.count > 0) {
                
                BingdingMyBoxCarViewController *vc = [[BingdingMyBoxCarViewController alloc] initWithVioCarModles:cars];
                [wself presentViewController:[UINavigationController navigationControllerWithRootViewController:vc] animated:YES completion:nil];
                __weak __typeof(vc) wvc = vc;
                vc.Click = ^(CarModel *model){
                    if (model) {
                        if (model.carinfoModel.carTypeId == 0) {
                            wself.carModel = model;
                            [wself.canChangeCarModel.carinfoModel fillModelWithDic:model.carinfoModel.modelDic];
                            wself.canChangeCarModel.carinfoModel.unDel = 1;
                            [wvc dismissViewControllerAnimated:YES completion:nil];
                        }else{
                            [NetCar bindCar:model.carinfoModel.id styleId:model.carinfoModel.carTypeId success:^{
                                [wvc dismissViewControllerAnimated:YES completion:^{
                                    if (wself.ClickDone) {
                                        wself.ClickDone();
                                    }
                                }];
                            }];
                        }
                    }else{
                        [wvc dismissViewControllerAnimated:YES completion:nil];
                    }
                };
            }
        } fail:nil];
        
    }
    
}
- (void)tapGesture
{
    [AlertMgr dismiss:TYPE_VIEW_ALERT];
}
/**
 *  是否能右滑返回手势
 */
-(BOOL)viewControllerShouldGesturePopBack
{
    return NO;
}
- (void)createTableView
{
    self.tableView.frame = CGRectMake(0, 0 , __MAIN_WIDTH , __MAIN_HEIGHT_64);
    self.tableView.backgroundColor = [Theme backGroundColor];
    self.tableView.separatorColor = [UIColor clearColor];
    
}
#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.titleArray[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 1 ? [BRCarStyleCell getCellHeight] : (indexPath.section == 2 ? SECTION_TITLE_HEIGHT : (indexPath.section == 3 ? [BRCarInfoCitySeleCell getCellHeight] : (indexPath.section == 4 ? [BRCarInfoCarBrandCell getCellHeight] : (indexPath.section == 5 ? [BRCarInfoCarNumCell getCellHeight] :(indexPath.section == 7 ? CELL_BTN_HEIGHT : ((indexPath.section == 0 ? SECTION_BIG_HEIGHT : CELL_GRAY_HEIGHT))))))));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell;
    switch (indexPath.section) {
        case 1://车型信息
        {
            NSString * cellID = @"BRCarStyleCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[BRCarStyleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                
            }
            CarInfoModel * model = self.canChangeCarModel.carinfoModel;
            NSString * carTypeStr = [NSString stringWithFormat:@"%@ %@\n%@",([model.brandName isNotNil] ? model.brandName : @""),([model.modelName isNotNil] ? model.modelName : @"") , ([model.styleName isNotNil] ? model.styleName : @"")];
            if (self.canChangeCarModel.carinfoModel.modelDic.count > 0 && [model.brandName isNotNil]) [((BRCarStyleCell *)cell) reloadIconImageUrl:self.canChangeCarModel.carinfoModel.modelImg title:carTypeStr];
        }
            break;
        case 2:
        {
            NSString * cellID = @"sectionTitleCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                cell.backgroundColor = [Theme backGroundColor];
                CGFloat labelX = 15 * __MAIN_RATIO_375;
                [[UILabel labelWithFrame:CGRectMake(labelX, 0, __MAIN_WIDTH - labelX * 2, SECTION_TITLE_HEIGHT) font:FONT_DEFAULT_Light(12) text:self.titleArray[indexPath.section][indexPath.row] textColor:COLOR_HEXSTRING(@"#a5a5a5")] setupOnView:cell];
            }
        }
            break;

        case 3://查询城市
        {
            NSString * cellID = @"QueryCitySeleCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[BRCarInfoCitySeleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            [((BRCarInfoCitySeleCell *)cell)reloadleftTitle:self.titleArray[indexPath.section][indexPath.row] rightTItle:([self.canChangeCarModel.showCitys isNotNil]) ? self.canChangeCarModel.showCitys : @"请选择查询城市"];
            
        }
            break;
        case 4://车牌号码
        {
            NSString * cellID = @"BRCarInfoCarBrandCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[BRCarInfoCarBrandCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                CGFloat viewX = 9;
                [[[UIView viewWithFrame:CGRectMake(viewX, [BRCarInfoCarBrandCell getCellHeight] - 0.5, __MAIN_WIDTH - viewX * 2 , 0.5)] setupOnView:cell] resetBackgroundColor:[Theme lineColor]];
            }
            self.brandCityL = ((BRCarInfoCarBrandCell *)cell).simpleCityL;
            self.brandRightImageV = ((BRCarInfoCarBrandCell *)cell).cityImageV;
            
            self.brandCityL.text = ([self.canChangeCarModel.carinfoModel.carNoCityStr isNotNil] ? self.canChangeCarModel.carinfoModel.carNoCityStr : @"沪");
            
            __weak __typeof(self) wself = self;
            ((BRCarInfoCarBrandCell *)cell).cityVClick = ^()
            {//选择车牌所属城市
                [wself.tableView endEditing:YES];
                [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    wself.cityNamesBackV.hidden = !wself.cityNamesBackV.hidden;

                    wself.carCityV.hidden = !wself.carCityV.hidden;
                    wself.carCityV.bottom = __MAIN_HEIGHT;
                    wself.brandRightImageV.transform = CGAffineTransformMakeRotation(wself.carCityV.hidden ? 0 : M_PI);
                    
                    //                    [wself.cityNamesBackV setHeight:__MAIN_HEIGHT - wself.carCityV.height];
                } completion:nil];
            };
            self.carCityV.hidden = YES;
            
            [self registerTextField:((BRCarInfoCarBrandCell *)cell).rightTF];
            self.brandNoTF = ((BRCarInfoCarBrandCell *)cell).rightTF;
            
            if ([self.canChangeCarModel.carinfoModel.carNoNumStr isNotNil])[((BRCarInfoCarBrandCell *)cell).rightTF setText:self.canChangeCarModel.carinfoModel.carNoNumStr];
        }
            break;
        case 5://发动机号，车架号
        {
            NSString * cellID = @"BRCarInfoCarNumCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[BRCarInfoCarNumCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            
            [self registerTextField:((BRCarInfoCarNumCell *)cell).engineNOTF];
            [self registerTextField:((BRCarInfoCarNumCell *)cell).classaNOTF];
            
            self.engineNOTF = ((BRCarInfoCarNumCell *)cell).engineNOTF;
            self.classNoTF = ((BRCarInfoCarNumCell *)cell).classaNOTF;
            
            if([self.canChangeCarModel.carinfoModel.ecode isNotNil]) [((BRCarInfoCarNumCell *)cell).engineNOTF setText:self.canChangeCarModel.carinfoModel.ecode];
            if([self.canChangeCarModel.carinfoModel.vcode isNotNil]) [((BRCarInfoCarNumCell *)cell).classaNOTF setText:self.canChangeCarModel.carinfoModel.vcode];
            
            __weak __typeof(self) wself = self;
            ((BRCarInfoCarNumCell *)cell).questionBtnClick = ^()
            {
                [wself clickOnBG];
                [wself.popExampleImageV animationHidden:NO];
            };
        }
            break;
        case 7://保存按钮
        {
            NSString * cellID = @"saveBtnCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                cell.backgroundColor = [Theme backGroundColor];
                
                CGFloat btnX = 11 * __MAIN_RATIO_375;
                //保存按钮
                __weak __typeof(self) wself = self;
                [[[[UIButton buttonWithFrame:CGRectMake(btnX, 0, __MAIN_WIDTH - btnX * 2, CELL_BTN_HEIGHT) title:self.buttonTitle textColor:[UIColor whiteColor] font:FONT_DEFAULT_Light(16) click:^{
                    [wself clickOnBG];
                    [wself saveBtnClick];
                    
                }] setupOnView: cell] resetBackgroundColor:[Theme mainNavColor]] resetCornerRadius:2];
            }
        }
            break;
        case 0:
        case 6:
        case 8:
        {
            NSString * cellID = @"noCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                cell.backgroundColor = [Theme backGroundColor];
            }
        }
            break;
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self clickOnBG];
    
    switch (indexPath.section) {
        case 1://选择车辆信息
        {
            if (![Check isVisiter]) {
                ChoiceCarInfoViewController *vc = [[[ChoiceCarInfoViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE carModel:self.canChangeCarModel.carinfoModel] navSetupBackItemWithIdentification:BACK_ICON];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 3://点击城市
        {
            BRSelectCityViewController * selectVC = [[BRSelectCityViewController alloc]initWithData:self.cityMgr.provinceModels clickCityData:self.canChangeCarModel.cityModels];
            selectVC.delegate = self;
            [self.navigationController pushViewController:[selectVC navSetupBackItemWithIdentification:BACK_ICON] animated:YES];
        }
            break;
            
        default:
            break;
    }

}
#pragma mark - selectCity delegate
- (void)configClickCityModels:(NSArray *)cityModels
{
    self.canChangeCarModel.cityModels = cityModels;
    [self.tableView reloadData];
    
    __weak __typeof(self) wself = self;
    if (self.canChangeCarModel.needIDNum) {
        [self isNeedsInputAlert:^(NSString *text) {
            wself.canChangeCarModel.carinfoModel.idnum = text;
        }];
    }
}
#pragma mark - 保存按钮

-(void)resetBindingClickDone:(void (^)())clickDone{
    self.buttonTitle = @"绑定";
    self.canChangeCarModel.carinfoModel.unDel = 1;
    self.ClickDone = clickDone;
    self.isBinding = YES;
    [self.tableView reloadData];
}

- (void)saveBtnClick
{
    [UmengMgr event:ICZ_CarMgrSaveCar];
    [[StatisticsMgr sharedInstance] addClickID:@"车辆管理－保存车辆按钮" description:@""];
    
    __weak __typeof(self) wself = self;
    if (self.canChangeCarModel.carinfoModel.modelDic.count == 0) {
        [AlertMgr showShortTextTips:@[@"请选择车型"]];
        return;
    }
    
//    if (self.canChangeCarModel.cityModels.count == 0) {
//        [AlertMgr showShortTextTips:@[@"请选择查询城市"]];
//        return;
//    }

    if ([self.brandNoTF.text isNotNil]) {
        if (![Check isNumOrBigASCIILength:self.brandNoTF.text] ) {
            return;
        }
        if (![Check isNumOrBigASCIIEngionNOLength:self.engineNOTF.text]) {
            return;
        }
        if (![Check isNumOrBigASCIICarFrameLength:self.classNoTF.text]) {
            return;
        }
        self.canChangeCarModel.carinfoModel.carNoCityStr = self.brandCityL.text;
        self.canChangeCarModel.carinfoModel.carNoNumStr = self.brandNoTF.text;
        self.canChangeCarModel.carinfoModel.ecode = self.engineNOTF.text;
        self.canChangeCarModel.carinfoModel.vcode = self.classNoTF.text;
    }
    
    if (self.carModel.modelDic.count > 0) {//更新carmodel
        
        if (self.canChangeCarModel.carinfoModel.carTypeId != self.carModel.carinfoModel.carTypeId) {
            self.canChangeCarModel.carinfoModel.isChangeCarStyle = YES;
        }
        
        [NetCar updateCar:self.canChangeCarModel.carinfoModel.modelDic success:^{
            wself.carModel = wself.canChangeCarModel;
            if (wself.ClickDone) {
                wself.ClickDone();
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else//新增car model
    {
        [NetCar addCar:self.canChangeCarModel.carinfoModel.modelDic success:^{
            [wself.tableView reloadData];
            wself.carModel = wself.canChangeCarModel;
            if (wself.ClickDone) {
                wself.ClickDone();
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}
-(BOOL)textFieldCanAddString:(NSString *)string withTextField:(UITextField *)textField
{
    if (textField == self.brandNoTF) {
        if (![Check isNumOrBigASCII:string]) {
            return NO;
        }
    }
    if (textField == self.engineNOTF && self.engineNOTF) {
        if (![Check isNumOrBigASCIIEngionNO:string]) {
            return NO;
        }
    }
    if (textField == self.classNoTF && self.classNoTF) {
        if (![Check isNumOrBigASCIICarFrame:string]) {
            return NO;
        }
    }
    return YES;
}
- (NSInteger)textFieldMaxNumberWithTextField:(UITextField *)textField
{
    if (textField == self.brandNoTF)
    {
        return 5;
    }
    else if(textField == self.engineNOTF)
    {
        return 20;
    }
    else if(textField == self.classNoTF)
    {
        return 20;
    }
    else
    {
        return [super textFieldMaxNumberWithTextField:textField];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self clickOnBG];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if((![self.canChangeCarModel.carinfoModel.brandName isNotNil]) && self.willPushCarStyle)
    {
        [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        self.willPushCarStyle = NO;
    }
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
     __weak __typeof(self) wself = self;
    if (self.canChangeCarModel.needIDNum) {
        [self isNeedsInputAlert:^(NSString *text) {
            wself.canChangeCarModel.carinfoModel.idnum = text;
        }];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self clickOnBG];
}
#pragma mark 进入此页面后或选择城市后 要判断是否填写身份证号 
- (void)isNeedsInputAlert:(void(^)(NSString * text))input
{

    TipsInputView * view = [[TipsInputView alloc]init];
    [view reloadTitle:@"交管局需核实车主信息" withInputArray:@[@"请输入身份证号"] withClick:^(NSArray *inputTextArr) {
        if ([Check isIDCard:inputTextArr[0]]) {
            if (input) input(inputTextArr[0]);
            [AlertMgr dismiss:TYPE_VIEW_ALERT];
        }
        
    }];
    [AlertMgr showView:view];
}
#pragma mark 用于控制车牌号前面城市简称选择的控制
- (void)clickOnBG{
    [super clickOnBG];
    
    __weak __typeof(self) wself = self;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        wself.carCityV.top = __MAIN_HEIGHT;
        wself.carCityV.hidden = YES;
        wself.cityNamesBackV.hidden = YES;
        if(wself.brandRightImageV)wself.brandRightImageV.transform = CGAffineTransformMakeRotation(0);
    } completion:nil];
}
- (void)keyBoardWillShow{
    __weak __typeof(self) wself = self;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        wself.carCityV.top = __MAIN_HEIGHT;
        wself.carCityV.hidden = YES;
        wself.cityNamesBackV.hidden = YES;
        if(wself.brandRightImageV)wself.brandRightImageV.transform = CGAffineTransformMakeRotation(0);
    } completion:nil];
}
- (PopExampleImageV *)popExampleImageV
{
    if (!_popExampleImageV) {
        _popExampleImageV = [[PopExampleImageV alloc]init];
    }
    return _popExampleImageV;
}
- (UIView *)cityNamesBackV
{
    if (!_cityNamesBackV) {
        _cityNamesBackV = [[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, __MAIN_HEIGHT)] resetBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.6]];
    }
    return _cityNamesBackV;
}
- (NSArray *)titleArray
{
    return @[@[@"空白"],@[@"车型信息"],@[@"查违章信息"],@[@"查询城市"],@[@"车牌号码"],@[@[@"发动机号",@"车架号码"]],@[@"空白"],@[@"保存"],@[@"空白"]];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
